package com.central.apps.handler.timeTask;

import com.central.app.common.quartz.QuartzJob;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.apps.dao.MaterialInventory.QueryDao;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Slf4j
//禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
@DisallowConcurrentExecution
public class QueryTask extends QuartzJob {

    @Autowired
    private QueryDao queryDao;
    @Autowired
    private HandlerService handlerService;

    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) throws JobExecutionException {
        //查询当月需要结算的库存
        String dateStr = DateUtils.dateToStr(new Date(), "yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        List<Map<String, Object>> invbalancesList = queryDao.findInvbalances();
        if (CollectionUtils.isEmpty(invbalancesList)) {
            log.info("没有需要生成的库存月结");
            return;
        }
        //根据库存分组
        List<Map<String, Object>> invbalancesListReNull = invbalancesList.stream().filter(map -> {
            String storenum = MapUtils.getString(map, "storenum");
            if (StringUtils.isNotBlank(storenum)) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        Function<Map<String, Object>, String> functionByStorenum = new Function<Map<String, Object>, String>() {
            @Override
            public String apply(Map<String, Object> map) {
                return map.get("storenum").toString();
            }
        };
        Map<String, List<Map<String, Object>>> invbalancesListByStorenum = invbalancesListReNull.stream().collect(Collectors.groupingBy(functionByStorenum));
        for (Map.Entry<String, List<Map<String, Object>>> entrie : invbalancesListByStorenum.entrySet()) {
            String key = entrie.getKey();
            List<Map<String, Object>> value = entrie.getValue();
            List<Map<String, Object>> bySql = handlerService.findBySql("select storedesc from gq_store where storenum ='" + key + "'");
            String storeDesc =MapUtils.getString(bySql.get(0),"storedesc");
            //新增月结查询主表
            Map<String, Object> invbalanceMap = new HashMap<>();
            handlerService.addBizNum("queryApp", "gq_query", invbalanceMap);
            invbalanceMap.put("querydesc", storeDesc + "月结记录");
            invbalanceMap.put("storenum", key);
            invbalanceMap.put("storedesc", storeDesc);
            invbalanceMap.put("year", year);
            invbalanceMap.put("month", month);
            Object id = null;
            log.info("111111111++++++++++++++++++++++++++++++++++++++"+invbalanceMap.toString());
            try {
                id = handlerService.insert("gq_query", invbalanceMap);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //新增子表
            DecimalFormat decimalFormat = new DecimalFormat("##0.00");
            BigDecimal totalcostDB = new BigDecimal("0");
            Integer totalnumber = 0;
            Integer totalcost =0;
            for (int i = 0; i < value.size(); i++) {
                Map<String, Object> querylineMap = value.get(i);
                querylineMap.put("queryid", id);
                String avgcost = MapUtils.getString(querylineMap, "avgcost"); //平均成本
                avgcost = (avgcost == null ? "0" : avgcost);
                Integer curbal = MapUtils.getInteger(querylineMap, "curbal");   //数量
                curbal = (curbal == null ? 0 : curbal);
                BigDecimal avgcostBD = new BigDecimal(avgcost);
                BigDecimal curbalBD = new BigDecimal(curbal);
                BigDecimal linecostBD = avgcostBD.multiply(curbalBD);
                String linecost = decimalFormat.format(linecostBD);
                querylineMap.put("linecost", linecost);
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select description,unit from gq_item where itemnum ='" + MapUtils.getString(querylineMap,"itemnum") + "'");
                String description =MapUtils.getString(bySql.get(0),"description");
                String unit =MapUtils.getString(bySql.get(0),"unit");
                querylineMap.remove("itemdesc");
                querylineMap.put("itemdesc",description);
                querylineMap.remove("unit");
                querylineMap.put("unit",unit);
                log.info("2222222++++++++++++++++++++++++++++++++++++++"+invbalanceMap.toString());
                queryDao.insertToQueryline(querylineMap);
                totalcostDB.add(linecostBD);
                totalnumber = totalnumber + curbal;
                totalcost =totalcost +MapUtils.getInteger(querylineMap,"linecost");
            }
            //更新主表数量和成本
            //String totalcost = decimalFormat.format(totalcostDB);
            queryDao.updateQuery(totalnumber, Integer.toString(totalcost));

        }
    }
}
